package com.ruoyi.back.service.impl

import cn.hutool.core.util.StrUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.ruoyi.app.common.Data
import com.ruoyi.app.common.Ok
import com.ruoyi.back.domain.ChannelManager
import com.ruoyi.back.mapper.ChannelManagerMapper
import com.ruoyi.back.service.ChannelFunctionService
import com.ruoyi.back.service.ChannelManagerService
import com.ruoyi.common.core.page.TableSupport
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class ChannelManagerServiceImpl : ServiceImpl<ChannelManagerMapper, ChannelManager>(), ChannelManagerService {

    @Autowired
    private lateinit var channelFunctionService: ChannelFunctionService

    override fun saveChannelManager(channelManager: ChannelManager): Data<Boolean> =
        channelManager.id?.run {
            Ok("更新成功", kotlin.run {
                updateById(channelManager)
                channelFunctionService.updateChannelFunctions(channelManager.functionIds, channelManager.id!!)
            })
        } ?: Ok("保存成功", kotlin.run {
            save(channelManager)
            channelFunctionService.updateChannelFunctions(channelManager.functionIds, channelManager.id!!)
        })

    override fun channelManagerPage(channelManager: ChannelManager): Page<ChannelManager> =
        TableSupport.buildPageRequest().let { pageDomain ->
            page(
                Page(pageDomain.pageNum.toLong(), pageDomain.pageSize.toLong()),
                KtQueryWrapper(ChannelManager::class.java)
                    .eq(StrUtil.isNotBlank(channelManager.name), ChannelManager::name, channelManager.name)
            )
                .let { page: Page<ChannelManager> ->
                    page.apply {
                        records = page.records.takeIf { it.isNotEmpty() }
                            ?.run {
                                map {
                                    it.apply {
                                        functionShow = channelFunctionService.getFunctionStrByChannel(it.id!!)
                                        functionIds = channelFunctionService.getFunctionIdsByChannel(it.id!!)
                                        functionInfos = channelFunctionService.getFunctionInfoByChannel(it.id!!)
                                    }
                                }
                            }
                    }
                }
        }

    override fun removeChannelManager(channelIds: String): Data<Boolean> =
        Ok("批量移除成功", removeByIds(channelIds.split(",")))
}